package com.yuanlang.common.util;

import org.apache.commons.codec.binary.Hex;
import org.slf4j.Logger;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.security.SecureRandom;

import static org.slf4j.LoggerFactory.getLogger;

/**
 * Created by lvluogang on 2017/6/12.
 */
public class AESUtil {
    private static final Logger log = getLogger(AESUtil.class);

    public static Key getSecretKey(String key) throws Exception{
        if(key == null){
            key = "";
        }
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        SecureRandom random=SecureRandom.getInstance("SHA1PRNG");
        random.setSeed(key.getBytes());
        keyGenerator.init(128,random);
        SecretKey securekey = keyGenerator.generateKey();
        byte[] enCodeFormat = securekey.getEncoded();
        SecretKeySpec keySpec = new SecretKeySpec(enCodeFormat, "AES");
        return keySpec;
    }

    public static byte[] encrypt(byte[] data,String key) throws Exception {
        Key securekey = getSecretKey(key);
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, securekey);
        return cipher.doFinal(data);
    }

    public static String encryptAsBase64(String data,String key){
        try {
            byte[] bt=encrypt(data.getBytes(StandardCharsets.UTF_8),key);
            return new BASE64Encoder().encode(bt);
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            return null;
        }
    }

    public static String encryptAsHex(String data,String key){
        try {
            byte[] bt=encrypt(data.getBytes(StandardCharsets.UTF_8),key);
            return new String(Hex.encodeHex(bt));
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            return null;
        }
    }


    public static byte[] decrypt(byte[] data,String key) throws Exception{
        Key securekey = getSecretKey(key);
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, securekey);
        return cipher.doFinal(data);
    }

    public static String decryptFromBase64(String data,String key){
        try {
            byte[] res=decrypt(new BASE64Decoder().decodeBuffer(data),key);
            return new String(res);
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            return null;
        }
    }

    public static String decryptFromHex(String data,String key){
        try {
            byte[] res=decrypt(Hex.decodeHex(data.toCharArray()),key);
            return new String(res);
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            return null;
        }
    }

    public static void main(String[] args)throws Exception{
        String message = "passwo阿斯顿发大水rd";
        String key = "1dsd&";
        String entryptedMsg = encryptAsBase64(message,key);
        System.out.println("encrypted message is below :");
        System.out.println(entryptedMsg);

        String decryptResult = decryptFromBase64(entryptedMsg,key);
        System.out.println("decrypted message is below :");
        System.out.println(new String(decryptResult));

    }
}
